package com.learning.netease.readingwritingseparation.datasource;

import lombok.Getter;
import lombok.Setter;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * ClassName: DynamicDataSource
 * Description: 动态数据源
 * Date: 2019/3/29 15:56 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
@Setter
@Getter
public class DynamicDataSource extends AbstractRoutingDataSource {


    private DataSource writeDataSource;
    private DataSource readDataSource;


    @Override
    public void afterPropertiesSet() {
        if (Objects.isNull(this.writeDataSource)) {
            throw new IllegalArgumentException("Properties 'writeDataSource' is required");
        }

        // 设置默认目标数据源
        setDefaultTargetDataSource(this.writeDataSource);

        // 设置目标数据源
        Map<Object, Object> targetDataSource = new HashMap<>(16);
        targetDataSource.put(DynamicDataSourceGlobel.WRITE.name(), this.writeDataSource);

        if (Objects.nonNull(this.readDataSource)) {
            targetDataSource.put(DynamicDataSourceGlobel.READ.name(), this.readDataSource);
        }
        setTargetDataSources(targetDataSource);

        super.afterPropertiesSet();
    }

    /**
     * 数据源切换
     *
     * @return
     */
    @Override
    protected Object determineCurrentLookupKey() {
        DynamicDataSourceGlobel dataSource = DynamicDataSourceHolder.getDataSource();
        if (Objects.isNull(dataSource) || dataSource == DynamicDataSourceGlobel.WRITE) {
            return DynamicDataSourceGlobel.WRITE.name();
        }
        return DynamicDataSourceGlobel.READ.name();
    }


}
